<template>
  <el-card class="el-card--has-heading success">
    <div slot="header">
      <span>系统配置</span>
      <el-button
        style="float: right; padding: 3px 0"
        type="text"
        @click="onClickCreate"
        v-auth:[$P.system.role.create]
      >创建配置</el-button>
    </div>
    <v-table
      :dataSource="dataSource"
      :columns="filterColumn(columns,[$P.system.role.update, $P.system.role.delete])"
      :loading="loading"
      v-bind="bindProps"
      v-on="bindListeners"
    ></v-table>

    <Modal
      :title="configModalType === 'create' ? $t('createText') : $t('updateText')"
      :loading="configModalLoading"
      :visible.sync="configModalVisible"
      :width="$V.size.sm"
      :onOk="handleConfigSubmit"
      :onCancel="handleConfigClose"
      :okText="configModalType === 'create' ? $t('createText') : $t('updateText')"
    >
      <ConfigForm :record="record" :types="configTypeList" ref="ConfigForm" />
    </Modal>
  </el-card>
</template>

<script>
import ConfigForm from './components/ConfigForm'
import {
  getSystemConfigList,
  createSystemConfig,
  updateSystemConfig,
  getSystemConfigById,
  deleteSystemConfig,
  getSystemConfigSelects
} from '@/api'
import { Query } from '@/mixins'

import { primaryKey } from './model'

export default {
  mixins: [Query('query')],

  components: { ConfigForm },
  data () {
    return {
      dataSource: [],
      loading: false,
      columns: [
        { prop: 'configurationName', label: '配置项' },
        { prop: 'configurationKey', label: '配置项编码' },
        { prop: 'configurationValue', label: '配置值' },
        { prop: 'configurationCreateTime', label: '创建时间', width: this.$V.cellSize.date, formatter: row => this.$formatTime(row['configurationCreateTime']) },
        { prop: 'configurationCreateUserName', label: '创建人' },
        { prop: 'configurationUpdateTime', label: '修改时间', width: this.$V.cellSize.date, formatter: row => this.$formatTime(row['configurationUpdateTime']) },
        { prop: 'configurationUpdateUserName', label: '修改人' },
        {
          label: '操作',
          minWidth: this.$V.cellSize.action,

          formatter: this.getActionDecorator([
            {
              icon: 'el-icon-edit',
              action: this.onClickUpdate,
              auth: this.$P.system.role.update,
              type: 'primary'
            },
            {
              icon: 'el-icon-delete',
              action: this.onClickDelete,
              auth: this.$P.system.role.delete,
              type: 'danger'
            }
          ])
        }
      ],
      row: null,

      // -------- Config Modal ----------
      configTypeList: [],
      record: {},
      configModalType: '',
      configModalVisible: false,
      configModalLoading: false
      // -------- !Config Modal ----------
    }
  },
  methods: {
    // Requests
    // ------------------------------------------
    getSystemConfigList (fn) {
      return this.Catch(getSystemConfigList, {
        onOk (res) {
          this.dataSource = res.data
        }
      })('loading', (fn || this.$noop)(this.query))
    },

    getSystemConfigById (id, { onOk, onError }) {
      return this.Catch(getSystemConfigById, {
        onOk,
        onError
      })('loading', id)
    },

    getSystemConfigSelects ({ onOk, onError } = {}) {
      return this.Catch(getSystemConfigSelects, {
        onOk ({ data }) {
          this.configTypeList = data.map(it => ({
            label: it.value,
            value: it.code,
            ori: it
          }))
        },
        onError
      })('loading')
    },

    createSystemConfig (data) {
      return this.Catch(createSystemConfig, {
        onOk () {
          this.$message.success(this.$t('createOk'))
          this.getSystemConfigList()
          this.configModalVisible = false
        }
      })('configModalLoading', data)
    },

    updateSystemConfig (id, data) {
      return this.Catch(updateSystemConfig, {
        onOk () {
          this.$message.success(this.$t('updateOk'))
          this.getSystemConfigList()
          this.configModalVisible = false
        }
      })('configModalLoading', id, data)
    },

    deleteSystemConfig (id, { onOk }) {
      return this.Catch(deleteSystemConfig, {
        onOk
      })(null, id)
    },

    // Table
    // ------------------------------------------

    onClickDelete (row) {
      this.ConfirmDelete({
        onOk: () =>
          this.deleteSystemConfig(row[primaryKey], {
            onOk () {
              this.$message.success(this.$t('deleteOk'))
              this.getSystemConfigList()
            }
          })
      })
    },

    async onClickUpdate (row) {
      await this.ensureSelectDataReady()

      this.getSystemConfigById(row[primaryKey], {
        onOk ({ data }) {
          this.configModalType = 'update'
          this.record = data
          this.configModalVisible = true
        }
      })
    },

    async onClickCreate () {
      await this.ensureSelectDataReady()

      this.configModalType = 'create'
      this.record = {}
      this.configModalVisible = true
    },

    // Modal
    // ------------------------------------------
    ensureSelectDataReady () {
      if (this.configTypeList.length) return Promise.resolve()
      return this.getSystemConfigSelects()
    },

    // 关闭modal清理数据
    handleClose () {
      this.visible = false
    },

    handleConfigSubmit () {
      this.$refs.ConfigForm.submit((valid, values) => {
        if (valid) {
          if (this.configModalType === 'create') {
            this.createSystemConfig(values)
          } else {
            this.updateSystemConfig(values[primaryKey], values)
          }
        }
      })
    },

    handleConfigClose () {
      this.configModalVisible = false
      this.record = {}
      this.configModalType = ''
    }
  },
  computed: {},

  created () {
    this.getSystemConfigList()
    this.inject(this.getSystemConfigList)
  }
}
</script>
